#include <QtGui/QApplication>
#include <QtCore>
#include <QtScript>
#include <QMessageBox>
#include <QtXml>
#include <QXmlStreamReader>
#include <QScriptEngine>
#include <QList>
#include <QTextStream>
#include <QSettings>
#include <QProgressDialog>

#include "defines.h"
#include "databasemanager.h"
#include "scriptmanager.h"
#include "abstractcontainer.h"
#include "abstractstorage.h"
#include "workbench.h"
#include "settings.h"
#include "uiloader.h"
#include "scriptfunctions.h"
#include "projectsettings.h"
#include "../network/communicator.h"

Workbench* Workbench::m_instance = 0;

Workbench::Workbench() :
    QObject(),
    m_settings(Settings::instance())
{
    m_databaseManager = DatabaseManager::instance();
    m_scriptManager = ScriptManager::instance();

//    m_projectFile = "/home/cher/Mobile/WorkBench/testLogin/";
#ifdef Q_OS_ANDROID
    m_projectFile = "/mnt/sdcard/.uiscripter/audit/Project1.sp";
#else
    m_projectFile = "c:/QtMobileScript/Project1.sp";
#endif

    if ( m_projectFile.isEmpty() ) {
         ProjectSettings w;
         w.exec();
    }
}

Workbench::~Workbench()
{
    delete m_settings;
    delete m_scriptManager;
    delete m_databaseManager;
}

void Workbench::loadProject(const QString &projectFile)
{    
    bool res;
    if(projectFile.length() > 0)
        m_projectFile = projectFile;

    res = readProjectFile(m_projectFile);

    if( res ) {
        m_scriptManager->initScriptLibrary();
        AbstractContainer* dbcontainer = m_project.containerByName(XML_DATABASES);
        res = m_databaseManager->initDatabases(dbcontainer);
        if( res ) {
            loadOtherScripts();
            loadMainScript(m_projectFolder + m_project.property(XML_PROJECTSCRIPT).toString());
        }
    }
}

bool Workbench::readProjectFile(QString projectFile)
{
    bool res = true;
    QFile xfile;
    xfile.setFileName(projectFile);    
    QXmlStreamReader xml;
    xml.setDevice(&xfile);
    qDebug()<<"Open project: "<<projectFile;
    if( !xfile.open(QFile::ReadOnly | QFile::Text) ) {
       QMessageBox::critical(0, "Error", "Невозможно прочитать файл проекта!\n"+projectFile,QMessageBox::Close);
       res = false;
    } else {
    #ifdef Q_OS_WIN
        m_projectFile.replace('\\','/');
    #endif
       int p1 = m_projectFile.lastIndexOf('/');
       m_projectFolder = m_projectFile.left(p1+1);
       res = m_project.readFromXml(&xml);
    }

    xfile.close();
    return res;
}

Workbench * Workbench::instance()
{
    if(m_instance == 0)
        m_instance = new Workbench();

    return m_instance;
}

void Workbench::loadMainScript(const QString &scriptFile)
{
    m_scriptManager->loadScriptFile(scriptFile);
    m_scriptManager->invokeFunction("main");
}

QWidget* Workbench::loadForm(int formIndex)
{
    AbstractContainer* forms = m_project.containerByName(XML_FORMSLIST);
    if (formIndex < forms->size()) {
        AbstractStorage* form = forms->at(formIndex);
        AbstractContainer* cons = form->containerByName(XML_CONNECTIONS);
        QString formname = m_projectFolder + form->property(XML_FORMFILE).toString();
        return loader.load(formname, cons); // Load form from UI file and connect signals to Script funcions
    }
    return 0;
}

void Workbench::loadOtherScripts()
{
    AbstractContainer* forms = m_project.containerByName(XML_FORMSLIST);
    for (int i = 0; i < forms->size(); i++) {
        AbstractStorage* form = forms->at(i);
        QString scriptname = m_projectFolder + form->property(XML_SCRIPTFILE).toString();
        m_scriptManager->loadScriptFile(scriptname);
    }
}

void Workbench::settingsDialog()
{
    ProjectSettings dlg;
    dlg.exec();
}
#include "inputdialog.h"
QVariant Workbench::inputDialog(const QString &label, const QString &value, QWidget *parent)
{
    InputDialog dlg(label, parent);
    return dlg.input(value);
}
#include "datedialog.h"
QVariant Workbench::dateDialog()
{
    DateDialog dlg;
    return dlg.getDate();
}
